package com.fr.plugin;

import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider;
import com.fr.decision.webservice.utils.DecisionServiceConstants;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.stable.StringUtils;
import com.fr.web.utils.WebUtils;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Base64;

@FunctionRecorder
public class MyGlobalRequestFilter extends AbstractGlobalRequestFilterProvider {

    @Override
    public String filterName() {
        return "everyThing";
    }

    @Override
    public String[] urlPatterns() {
        return new String[]{
                "/decision/*"
        };
    }

    // CAS认证，注册外部的类,不需要写doFilter了
//    @Override
//    public String externalFilterClassName() {
//        return "xxxx.xxx.class";
//    }

    @Override
    public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) {
        try {
            if(!isLogged(req)){
                // 获取token
                String myToken = req.getParameter("my_token");
                // 判断token是否为空
                if(StringUtils.isNotBlank(myToken)){
                    try{
                        String userName = new String(Base64.getUrlDecoder().decode(myToken));
                        UserService userService = UserService.getInstance();
                        // 检查用户是否存在
                        User user = userService.getUserByUserName(userName);
                        if(user != null){
                            // 登录并设置token到请求中
                            String token = LoginService.getInstance().login(req, res, userName);
                            req.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, token);
                        }else{
                            FineLoggerFactory.getLogger().error("登录用户不存在:{}",userName);
                            WebUtils.printAsString(res, "login user not exist:" + userName);
                            return;
                        }
                    }catch (Exception e){
                        FineLoggerFactory.getLogger().error("{} 登录过程异常",e);
                    }
                }
            }
            filterChain.doFilter(req,res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isLogged(HttpServletRequest request){
        return LoginService.getInstance().isLogged(request);
    }
}
